package com.wanqing.task;

import com.wanqing.entity.Orders;
import com.wanqing.mapper.OrderMapper;
import com.wanqing.mapper.VoucherMapper;
import com.wanqing.service.VoucherService;
import com.wanqing.service.impl.VoucherServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class OrderTask {
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private VoucherService voucherService;

    /**
     * 定时任务，处理超时订单
     */
    //@Scheduled(cron = "0 * * * * ?")
    public void processTimeoutOrders() {
        log.info("定时处理超时订单：{}", LocalDateTime.now());
        // 查询15分钟之前未支付订单
        LocalDateTime time = LocalDateTime.now().minusMinutes(15);
        List<Orders> ordersList = orderMapper.getByStatusAndTimeLT(Orders.PENDING_PAYMENT, time);
        // 遍历，更新订单状态
        if (ordersList != null && !ordersList.isEmpty()) {
            ordersList.forEach(orders -> {
                orders.setStatus(Orders.CANCELLED);
                orders.setCancelReason("支付超时");
                orders.setCancelTime(LocalDateTime.now());
                orderMapper.update(orders);
            });
        }
    }

    /**
     * 定时处理一直处于派送中的订单
     */
    //@Scheduled(cron = "0 0 1 * * ?")
    public void processDeliveryOrders() {
        log.info("定时处理处于派送中的订单：{}", LocalDateTime.now());
        LocalDateTime time = LocalDateTime.now().minusHours(1);
        List<Orders> ordersList = orderMapper.getByStatusAndTimeLT(Orders.DELIVERY_IN_PROGRESS, time);
        if (ordersList != null && !ordersList.isEmpty()) {
            ordersList.forEach(orders -> {
                orders.setStatus(Orders.COMPLETED);
                orders.setDeliveryTime(LocalDateTime.now());
                orderMapper.update(orders);
            });
        }
    }

    /**
     * 每小时执行一次检查过期优惠券的任务
     */
    @Scheduled(fixedRate = 12 * 60 * 60 * 1000) // 每小时执行一次（单位：毫秒）
    public void checkExpiredVoucher() {
        log.info("检查过期优惠券：{}", LocalDateTime.now());
        voucherService.checkExpiredUserVoucher();
        voucherService.checkExpiredVoucher();
    }
}
